$(function () {
    // create button
    $('#btn_create').click(function () {
        create();
    });
    $('#btn_edit').click(function () {
        finishSelect();
    });
    //1.初始化Table
    Init();

});

function create() {
    var content = $('#todo').val().trim();
    if (content == null || content == undefined || content == ''){
        $.fn.modalAlert('Please Fill The Content', 'danger');
        $('#todo').val('');
        $('#todo').focus();
        return;
    }
    data = "content="+content;
    $.ajax({
        url: "/morning/todolist/create",
        type: 'post',
        data: data,
        success: function () {
            $.fn.modalAlert('add todo item', 'success');
            $('#table').bootstrapTable('refresh');
            $('#todo').val('');
        },
        error: function () {
            $.fn.modalAlert('create error', 'danger');
            $('#todo').focus();
        }
    })
}

function Init() {

    $('#table').bootstrapTable({
        url: '../todolist/findAll',         //请求后台的URL（*）
        contentType: 'application/x-www-form-urlencoded',
        method: 'post',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        pagination: true,                   //是否显示分页（*）
        search: true,                       // 启用搜索
        toolbar: '#toolbar',                //工具按钮用哪个容
        //queryParams: oTableInit.queryParams,//传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*{
        // ）
        /*strictSearch: true,*/             // 精确搜索
        clickToSelect: true,                //是否启用点击选中行
        //height: height, // 行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        singleSelect: false,
        style:rowStyle,
        idField: 'topiclibraryid',
        columns: [
            {
                checkbox: true
            },
            {
                field: 'id',
                align: 'center',
                title: 'Id'
            },
            {
                field: 'content',
                align: 'center',
                title: 'Content'
            },{
                field: 'createTime',
                align: 'center',
                title: 'CreateTime',
                formatter: function (value, row, index) {
                    var time = row.createTime;
                    if (time == null) {
                        return "";
                    } else {
                        var rq = new Date(time);
                        return rq.toLocaleDateString();
                    }
                }
            },{
                field: 'lastUpdateTime',
                align: 'center',
                title: 'LastUpdateTime',
                formatter: function (value, row, index) {
                    var time = row.lastUpdateTime;
                    if (time == null) {
                        return "";
                    } else {
                        var rq = new Date(time);
                        return rq.toLocaleDateString();
                    }
                }
            },{
                field: 'flag',
                align: 'center',
                title: 'Status',
                formatter: function(value, row, index){
                    if (value === "1") {
                        return ' <a href="javascript:finish('+row.id+','+row.flag+');" class="btn btn-icon-only red"><span class="label label-sm label-success"> Done </span></a>';
                    }else {
                        return ' <a href="javascript:finish('+row.id+','+row.flag+');" class="btn btn-icon-only red"><span class="label label-sm label-danger"> ToDo </span></a>';
                    }
                }

            },{
                field: 'id',
                align: 'center',
                title: 'Action',
                formatter: function(value, row, index){
                    var edit  = ' <a href="javascript:edit();" class="btn btn-icon-only purple"><!--<i class="fa fa-edit"></i>--><span class="glyphicon glyphicon-pencil"></span></a>';
                    var remove = '<a href="javascript:remove('+value+');" class="btn btn-icon-only red"> <!--<i class="fa fa-refresh"></i>--><span class="glyphicon glyphicon-remove-circle"></span></a>';
                    return [edit+remove].join('');
                }
            }
            ]
    });
}

// var
//     $modal = $('#modal').modal({ show: false }),
//     $alert = $('.alert').hide();


/*function actionFormatter(value, row, index) {
    var edit  = ' <a href="javascript:edit();" class="btn btn-icon-only purple"><i class="fa fa-edit"></i><span class="glyphicon glyphicon-pencil"></span></a>';
    var remove ;
    if(row.flag == '0'){

        remove = '<a href="javascript:remove();" class="btn btn-icon-only red"> <i class="fa fa-refresh">1</i><span class="glyphicon glyphicon-remove"></span></a>';
    }else {
        remove = '<a href="javascript:remove();" class="btn btn-icon-only red"> <i class="fa fa-refresh">1</i><span class="glyphicon glyphicon-remove"></span></a>';
    }
    return [
        ' <a href="javascript:edit();" class="btn btn-icon-only purple"><i class="fa fa-edit"></i><span class="glyphicon glyphicon-pencil"></span></a>'+
        '<a href="javascript:remove();" class="btn btn-icon-only red"> <i class="fa fa-times"></i><span class="glyphicon glyphicon-remove"></span></a>',
    ].join('');
}*/

// finish todo
function finish(id,flag) {
    var data = "id="+id+"&flag="+flag;
    $.ajax({
        type: "POST",
        cache: false,
        async: true,
        dataType: "json",
        url: '/morning/todolist/finish',
        data: data,
        success: function () {
            $('#table').bootstrapTable('refresh');
            $.fn.modalAlert("change the status","success");
        },
        error: function () {
            $.fn.modalAlert("error","danger");
        }
    });
}
// finishSelect todo
function finishSelect() {
    var selRow = $('#table').bootstrapTable('getSelections');

    var ids = new Array();
    for(var i=0;i<selRow.length-1;i++){
        if(selRow[i].flag == 0 && selRow[i].id != 'undefined' && selRow[i].id != ''){
            ids[i]=selRow[i].id;
        }
    }
    var data = "ids="+ids;
    $.ajax({
        type: "POST",
        cache: false,
        async: true,
        dataType: "json",
        url: '/morning/todolist/finishSelect',
        data: data,
        success: function () {
            $('#table').bootstrapTable('refresh');
            $.fn.modalAlert("Done All Selected","success");
        },
        error: function () {
            $.fn.modalAlert("error","danger");
        }
    });
}
// remove todo, change deleteFlag as '1'
function remove(id) {
    var data = "id="+id;
    $.ajax({
        type: "POST",
        cache: false,
        async: true,
        dataType: "json",
        url: '/morning/todolist/remove',
        data: data,
        success: function () {
            $('#table').bootstrapTable('refresh');
            $.fn.modalAlert("remove this item","success");
        },
        error: function () {
            $.fn.modalAlert("error","danger");
        }
    });
}
// edit
function edit() {
    var selRow = $('#table').bootstrapTable('getSelections');
    if(selRow[0] == undefined || selRow[0] == null || selRow[0] == '' ){
        $.fn.modalAlert("please select item", "error");
        return;
    }
    var id = selRow[0].id;
    var content = selRow[0].content;
    var data = "id="+id+"&content="+content;
    modalOpen(id,content);
}
function modalOpen(id,content) {
    $.fn.modalOpen({
        id: "Form",
        title: 'Edit Todo',
        url: '../todolist/edit?id='+id+"&content="+content,
        width: "600px",
        height: "220px",
        callBack: function (iframeId) {
            var iframe = $(top.frames[iframeId].document);
            var index = iframeId.split('layui-layer-iframe')[1];
            var content = iframe.find('#content').val();
            var id = iframe.find('#id').val();
            var data = "id="+id+"&content="+content;
            $.ajax({
                type: "POST",
                cache: false,
                async: true,
                dataType: "json",
                url: '/morning/todolist/modify',
                data: data,
                success: function () {
                    $('#table').bootstrapTable('refresh');
                    top.layer.close(index);
                    $.fn.modalAlert("update this item","success");
                },
                error: function () {
                    $.fn.modalAlert("update error","danger");
                    iframe.find('#content').focus();
                }
            });
            return true;
        }
    });
};

function rowStyle(row, index) {
    var classes = ['active', 'success', 'info', 'warning', 'danger'];

    if (index % 2 === 0 && index / 2 < classes.length) {
        return {
            classes: classes[index / 2]
        };
    }
    return {};
}
// update and delete events
/*window.actionEvents = {
    'click #btn_add': function (e, value, row) {
        showModal($(this).attr('title'), row);
    },
    'click #btn_edit': function (e, value, row) {
        showModal($(this).attr('title'), row);
    },
    'click .btn_delete': function (e, value, row) {
        if (confirm('Are you sure to delete this item?')) {
            $.ajax({
                url: API_URL + row.id,
                type: 'delete',
                success: function () {
                    $('#table').bootstrapTable('refresh');
                    showAlert('Delete item successful!', 'success');
                },
                error: function () {
                    showAlert('Delete item error!', 'danger');
                }
            })
        }
    }
};*/

/*
function remove() {
    var selRow = $('#table').bootstrapTable('getSelections');
    var selectIndex = $('#table').bootstrapTable();
    if(selRow[0] == undefined || selRow[0] == null || selRow[0] == '' ){
        $.fn.modalAlert("please select item", "error");
        return;
    }
    var id = selRow[0].id;
    var flag = selRow[0].flag;
    var data = "id="+id+"&flag="+flag;
    if(selRow!=null){
        $.fn.modalConfirm("确认要提交么？", function(status) {
            if(status){
                $.ajax({
                    type: "POST",
                    cache:false,
                    async : true,
                    dataType : "json",
                    url:  '/morning/todolist/finish',
                    data: data,
                    success: function(data){
                        // show.close();
                        // $.fn.modalAlert("success");
                        if ( data[0].code == 0 ){
                            // $('#table').bootstrapTable('hideRow', {index:1});
                            $('#table').bootstrapTable('refresh');
                        }
                        // var a;
                    },
                    error:function () {
                        $.fn.modalAlert("error");
                    }
                });
            }
        });
        // return;
        $.fn.modalAlert("successaa");
    }else{
        alert('请选取要删除的数据行！');
    }
}*/
/*
function remove1(){
    var selRow = $table.bootstrapTable('getSelections');
    var idField = $table.bootstrapTable("getOptions").idField;
    var className = $table.bootstrapTable("getOptions").className;
    if(className!=null && className.length>0){
        className +="."
    }else{
        className = "";
    }
    var datas = className+idField+"="+eval('selRow[0].'+idField)+"&currenttime="+new Date().getTime();

    if(selRow!=null){
        qiao.bs.confirm({'title':'提示', 'msg':'此操作不可逆，确认删除第'+selectIndex+'行吗？'}, function(){
            $.ajax({
                type: "POST",
                cache:false,
                async : true,
                dataType : "json",
                url:  requestUrl,
                data: datas,
                success: function(data){
                    alert(data.mess);
                    if ( data.state == 200 ){
                        $table.bootstrapTable('hideRow', {index:selectIndex});
                        if(reLoad){
                            $table.bootstrapTable('refresh');
                        }
                    }
                }
            });
        })
    }else{
        alert('请选取要删除的数据行！');
    }
}*/